<?php

namespace App\Http\Controllers\Web;

use App\Models\Cases;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CasesController extends Controller
{
    public function index(Request $request)
    {
        $size = $request->input('size', 10);
        $query = Cases::query()->orderByRaw("ISNULL(`index`),`index` ASC")->orderBy("index");
        $search_text= $request->input("search_text");
        $email = $request->input("email");
        $phone = $request->input("phone");
        $query->when($search_text, function ($query) use ($search_text) {
            $query->where('title', "like", "%{$search_text}%");
        });
        $query->when($email, function ($query) use ($email) {
            $query->where('email', "like", "%{$email}%");
        });
        $query->when($phone, function ($query) use ($phone) {
            $query->where('phone', "like", "%{$phone}%");
        });

        return $this->successPaginate($query->paginate($size));
    }

    public function requestData(Request $request)
    {
        $requestData = $this->validate($request, [
            'index' => 'nullable',
            'title' => 'required',
            'title_en' => 'nullable',
            'cover_url' => "required",
            'abstract' => 'required',
            'abstract_en' => 'nullable',
            'tags' => 'nullable',
            'tags_en' => 'nullable',
            'content' => "required",
            'content_en' => 'nullable',
            'address' => 'required',
            'address_en' => 'nullable',
            'publish_date' => "required",
            'viewVolume' => 'nullable',
        ]);
        return $requestData;
    }

    public function show($id)
    {
        $case = Cases::query()->findOrFail($id);
        return $this->success($case);
    }

    public function viewVolume($id)
    {
        $case = Cases::query()->findOrFail($id);
        $viewVolume = $case->viewVolume;

        $case->viewVolume = $viewVolume + 1;
        $case->save();
        return $this->success($case);
    }

    public function store(Request $request)
    {
        $case = new Cases();
        $requestData = $this->requestData($request);
        $case->fill($requestData);
        $case->save();
        return $this->success($requestData);
    }

    public function update(Request $request, $id)
    {
        $case = Cases::query()->findOrFail($id);
        $requestData = $this->requestData($request);
        $case->fill($requestData);
        $case->save();
        return $this->success($requestData);
    }

    public function destroy($id)
    {
        $case = Cases::query()->findOrFail($id);
        $case->delete();
    }
}
